<?php

namespace Gql\Middleware;


use Gql\Contracts\MiddlewareInterface;
use Gql\Core\Context;

/**
 * 解析基础数据（通常用于解析标量数据）
 * Class GraphResolveBaseMiddleware
 * @package App\PhpGraph\Middleware
 */
class ResolveBaseMiddleware implements MiddlewareInterface
{

    public function handle(Context $ctx, callable $next)
    {
        $source = $ctx->preValue;
        $fieldName =snake_case($ctx->fieldName);
        $property = null;
        if ((is_array($source) || $source instanceof \ArrayAccess) && isset($source[$fieldName])) {

            $property = $source[$fieldName];

        } else if (is_object($source)) {
            if (isset($source->{$fieldName})) {
                $property = $source->{$fieldName};
            }
        }
        if ($property instanceof \Closure) {
            $ctx->body = call_user_func($property, $ctx);
        } else {
            $ctx->body = $property;
        }
        return $next($ctx);
    }
}